// pages/usersetting/usersetting.js
import api from '../../api/api'
import {
  urlObj
} from '../../api/url'
Page({

  /**
   * 页面的初始数据
   */
  data: {
    imgURl: '',
    userInfo: {
      memberName: '',
      memberTel: ''
    },
    index: 0,
    option: ['女', '男'],
    uploadFilePath:''
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.getUserProfile()
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },
  clickFile() {
    let _this = this;
    wx.chooseImage({
      success(res) {
        const tempFilePaths = res.tempFilePaths
        wx.uploadFile({
          url: urlObj.uploadImg, //仅为示例，非真实的接口地址
          filePath: tempFilePaths[0],
          name: 'file',
          formData: {
            // 'user': 'test'
          },
          success(result) {
            const resData = result.data;
            _this.setData({
              imgURl: `${urlObj.imgHost}${JSON.parse(resData).data.src}`,
              uploadFilePath:JSON.parse(resData).data.src
            })
          }
        })
      }
    })
  },
  getUserProfile() {
    api.get(urlObj.getUserInfo).then(res => {
      if (res.statusCode == '200') {
        let targetUrl = '';
        if(res.data.headImg.indexOf('http') >= 0) {
          targetUrl = res.data.headImg
        } else {
          targetUrl = `${urlObj.imgHost}${res.data.headImg}`
        }
        this.setData({
          userInfo: res.data,
          index: res.data.gender,
          imgURl: targetUrl
        })
      } else {
        wx.showToast({
          title: res.msg,//提示文字
          duration: 2000,//显示时长
          mask: true,//是否显示透明蒙层，防止触摸穿透，默认：false  
          icon: 'fail', //图标，支持"success"、"loading"  
        })
      }
    })
  },
  bindPickerChange: function (e) {
    this.setData({
      index: e.detail.value
    })
  },
  username(e) {
    let { value } = e.detail;
    const params = 'userInfo.memberName'
    this.setData({
      [params]: value
    })
  },
  phone(e) {
    let { value } = e.detail;
    const params = 'userInfo.memberTel'
    this.setData({
      [params]: value
    })
  },
  submitForm() {
    const params = {
      MemberName: this.data.userInfo.memberName || '',
      MemberHeadImg: this.data.uploadFilePath || this.data.userInfo.headImg || '',
      MemberTel: this.data.userInfo.memberTel || '',
      Gender: this.data.index 
    }
    api.post(urlObj.updateUserInfo, params).then(res => {
      if (res.statusCode == '200') {
        wx.showToast({
          title: res.msg,//提示文字
          duration: 2000,//显示时长
          mask: true,//是否显示透明蒙层，防止触摸穿透，默认：false  
          icon: 'none', //图标，支持"success"、"loading"  
        })
        setTimeout(() => {
          wx.switchTab({
            url: '../user/user',
          })
        }, 2000);
      } else {

      }
    })
  }
})